package com.bwie.ES.autoES;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.ES.pojo.esUser;
import com.bwie.pojo.User;
import com.bwie.service.impl.TbUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class ESrefresh implements ApplicationRunner {

    @Autowired
    TbUserServiceImpl tbUserService;

    @Autowired
    ElasticsearchRestTemplate esTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //检查es是否存在
        IndexOperations indexOperations = esTemplate.indexOps(esUser.class);
        if (!indexOperations.exists()){
            boolean b = indexOperations.create();
            Document mapping = indexOperations.createMapping();
            indexOperations.putMapping(mapping);
        }
        List<User> list = tbUserService.list();
        ArrayList<esUser> esUsers = new ArrayList<>();
        for (User user : list) {
            esUser esUser = BeanUtil.toBean(user, esUser.class);
            esUsers.add(esUser);
        }
        esTemplate.save(esUsers);
    }

    @Scheduled(cron = "0 0/1 * * * *")
    public void reEs(){
        List<User> list = tbUserService.list();
        ArrayList<esUser> esUsers = new ArrayList<>();
        for (User user : list) {
            esUser esUser = BeanUtil.toBean(user, esUser.class);
            esUsers.add(esUser);
        }
        esTemplate.save(esUsers);
    }
}
